<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型标识" prop="modelCode">
        <el-input
          v-model="queryParams.modelCode"
          placeholder="请输入模型标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模型类别" prop="modelType">
        <el-select v-model="queryParams.modelType" placeholder="请选择模型类别" clearable>
          <el-option label="属性" value="property" />
          <el-option label="功能" value="function" />
          <el-option label="事件" value="event" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:model:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:model:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:model:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:model:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模型名称" align="center" prop="modelName" />
      <el-table-column label="模型标识" align="center" prop="modelCode" />
      <el-table-column label="模型类别" align="center" prop="modelType">
        <template slot-scope="scope">
          <dict-tag :options="modelTypeOptions" :value="scope.row.modelType"/>
        </template>
      </el-table-column>
      <el-table-column label="数据类型" align="center" prop="dataType">
        <template slot-scope="scope">
          <dict-tag :options="dataTypeOptions" :value="scope.row.dataType"/>
        </template>
      </el-table-column>
      <el-table-column label="实时监测" align="center" prop="isMonitor">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.isMonitor ? 'success' : 'danger'">
            {{ scope.row.isMonitor ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="只读" align="center" prop="isReadonly">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.isReadonly ? 'success' : 'danger'">
            {{ scope.row.isReadonly ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="历史存储" align="center" prop="isHistory">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.isHistory ? 'success' : 'danger'">
            {{ scope.row.isHistory ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="数据定义" align="center" prop="dataDefine">
        <template slot-scope="scope">
          <div v-if="scope.row.dataDefine" class="data-define">
            <template v-if="scope.row.dataType == 'int' || scope.row.dataType == 'float'">
              <div>最大值: <span class="value">{{ JSON.parse(scope.row.dataDefine).max }}</span>, 最小值: <span class="value">{{ JSON.parse(scope.row.dataDefine).min }}</span></div>
              <div>步长: <span class="value">{{ JSON.parse(scope.row.dataDefine).step }}</span>, 单位: <span class="value">{{ JSON.parse(scope.row.dataDefine).unit }}</span></div>
            </template>
            <template v-else-if="scope.row.dataType == 'bool'">
              <div>0: <span class="value">{{ JSON.parse(scope.row.dataDefine).falseText }}</span>, 1: <span class="value">{{ JSON.parse(scope.row.dataDefine).trueText }}</span></div>
            </template>
            <template v-else-if="scope.row.dataType == 'enum'">
              <div v-for="(item, index) in JSON.parse(scope.row.dataDefine).enumList" :key="index">
                {{ item.value }}: <span class="value">{{ item.text }}</span>{{ index < JSON.parse(scope.row.dataDefine).enumList.length - 1 ? ',' : '' }}
              </div>
            </template>
            <template v-else-if="scope.row.dataType == 'string'">
              <div>最大长度: <span class="value">{{ JSON.parse(scope.row.dataDefine).maxLength }}</span></div>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:model:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:model:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入物模型名称，例如：温度" />
        </el-form-item>
        <el-form-item label="模型标识" prop="modelCode">
          <el-input v-model="form.modelCode" placeholder="请输入标识符，例如：temperature" />
        </el-form-item>
        <el-form-item label="模型排序" prop="modelSort">
          <el-input-number v-model="form.modelSort" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="模型类别" prop="modelType">
          <el-radio-group v-model="form.modelType" @change="handleModelTypeChange">
            <el-radio label="property">属性</el-radio>
            <el-radio label="function">功能</el-radio>
            <el-radio label="event">事件</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模型特性">
          <el-checkbox v-model="form.isMonitor">实时监测</el-checkbox>
          <el-checkbox v-model="form.isReadonly">只读数据</el-checkbox>
          <el-checkbox v-model="form.isHistory">历史存储</el-checkbox>
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-select v-model="form.dataType" placeholder="请选择数据类型">
            <el-option label="整数" value="int" />
            <el-option label="小数" value="float" />
            <el-option label="布尔" value="bool" :disabled="form.modelType == 'property'" />
            <el-option label="枚举" value="enum" :disabled="form.modelType == 'property'" />
            <el-option label="字符串" value="string" :disabled="form.modelType == 'property'" />
          </el-select>
        </el-form-item>
        <template v-if="form.dataType == 'bool'">
          <el-form-item label="布尔值">
            <el-col :span="11">
              <el-form-item prop="boolFalseText">
                <el-input v-model="form.boolFalseText" placeholder="例如：关闭" />
                <div class="sub-text">(0 值对应文本)</div>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">
              <span></span>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="boolTrueText">
                <el-input v-model="form.boolTrueText" placeholder="例如：打开" />
                <div class="sub-text">(1 值对应文本)</div>
              </el-form-item>
            </el-col>
          </el-form-item>
        </template>
        <template v-if="form.dataType == 'enum'">
          <el-form-item label="展示方式">
            <el-select v-model="form.enumDisplayType" placeholder="请选择展示方式">
              <el-option label="下拉框" value="select" />
              <el-option label="按钮" value="button" />
            </el-select>
          </el-form-item>
          <el-form-item label="枚举项">
            <div v-for="(item, index) in form.enumItems" :key="index" class="enum-item">
              <el-col :span="11">
                <el-input v-model="item.value" placeholder="参数值，例如：0" />
              </el-col>
              <el-col :span="11" :offset="1">
                <el-input v-model="item.text" placeholder="参数描述，例如：中速档位" />
              </el-col>
              <el-col :span="1">
                <el-button type="text" icon="el-icon-delete" @click="removeEnumItem(index)" />
              </el-col>
            </div>
            <el-button type="text" icon="el-icon-plus" @click="addEnumItem">添加枚举项</el-button>
          </el-form-item>
        </template>
        <template v-if="form.dataType == 'string'">
          <el-form-item label="最大长度" prop="maxLength">
            <el-input v-model="form.maxLength" placeholder="例如：1024" />
            <div class="sub-text">(字符串的最大长度)</div>
          </el-form-item>
        </template>
        <el-form-item label="取值范围" v-if="form.dataType == 'int' || form.dataType == 'float'">
          <el-col :span="11">
            <el-form-item prop="minValue">
              <el-input v-model.trim="form.minValue" placeholder="最小值" @input="handleValueInput" />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span>至</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="maxValue">
              <el-input v-model.trim="form.maxValue" placeholder="最大值" @input="handleValueInput" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="单位" v-if="form.dataType == 'int' || form.dataType == 'float'">
          <el-input v-model.trim="form.unit" placeholder="请输入单位，例如：℃" @input="handleValueInput" />
        </el-form-item>
        <el-form-item label="步长" v-if="form.dataType == 'int' || form.dataType == 'float'">
          <el-input-number v-model="form.step" :min="0" controls-position="right" placeholder="请输入步长，例如：1" @change="handleValueInput" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listModel, getModel, delModel, addModel, updateModel } from "@/api/iot/model";

export default {
  name: "Model",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物模型表格数据
      modelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 模型类别选项
      modelTypeOptions: [
        { dictLabel: "属性", dictValue: "property" },
        { dictLabel: "功能", dictValue: "function" },
        { dictLabel: "事件", dictValue: "event" }
      ],
      // 数据类型选项
      dataTypeOptions: [
        { dictLabel: "整数", dictValue: "int" },
        { dictLabel: "小数", dictValue: "float" },
        { dictLabel: "布尔", dictValue: "bool" },
        { dictLabel: "枚举", dictValue: "enum" },
        { dictLabel: "字符串", dictValue: "string" }
      ],
      // 是否选项
      yesNoOptions: [
        { dictLabel: "是", dictValue: true },
        { dictLabel: "否", dictValue: false }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        modelCode: null,
        modelType: null
      },
      // 表单参数
      form: {
        id: null,
        modelName: null,
        modelCode: null,
        modelSort: 0,
        modelType: 'property',
        dataType: null,
        isMonitor: false,
        isReadonly: false,
        isHistory: false,
        minValue: null,
        maxValue: null,
        unit: null,
        step: 1,
        boolFalseText: null,
        boolTrueText: null,
        enumDisplayType: 'select',
        enumItems: [],
        maxLength: 1024,
        dataDefine: null,
        remark: null
      },
      // 表单校验
      rules: {
        modelName: [
          { required: true, message: "模型名称不能为空", trigger: "blur" }
        ],
        modelCode: [
          { required: true, message: "模型标识不能为空", trigger: "blur" }
        ],
        modelType: [
          { required: true, message: "模型类别不能为空", trigger: "change" }
        ],
        dataType: [
          { required: true, message: "数据类型不能为空", trigger: "change" }
        ],
        minValue: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType == 'int' || this.form.dataType == 'float') {
                if (!value) {
                  callback(new Error('最小值不能为空'));
                } else if (isNaN(value)) {
                  callback(new Error('请输入数字'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        maxValue: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType == 'int' || this.form.dataType == 'float') {
                if (!value) {
                  callback(new Error('最大值不能为空'));
                } else if (isNaN(value)) {
                  callback(new Error('请输入数字'));
                } else if (Number(value) <= Number(this.form.minValue)) {
                  callback(new Error('最大值必须大于最小值'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        maxLength: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType == 'string') {
                if (!value) {
                  callback(new Error('最大长度不能为空'));
                } else if (isNaN(value)) {
                  callback(new Error('请输入数字'));
                } else if (Number(value) <= 0) {
                  callback(new Error('最大长度必须大于0'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        boolFalseText: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType == 'bool' && !value) {
                callback(new Error('请输入0值对应文本'));
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        boolTrueText: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType == 'bool' && !value) {
                callback(new Error('请输入1值对应文本'));
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物模型列表 */
    getList() {
      this.loading = true;
      listModel(this.queryParams).then(response => {
        this.modelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 处理数值输入
    handleValueInput(value) {
      // 强制更新视图
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    // 监听模型类别变化
    handleModelTypeChange() {
      // 当切换到属性类型时，如果当前数据类型不是整数或小数，则重置为null
      if (this.form.modelType == 'property' && 
          this.form.dataType != 'int' && 
          this.form.dataType != 'float') {
        this.form.dataType = null;
      }
      // 强制更新视图
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        modelName: null,
        modelCode: null,
        modelSort: 0,
        modelType: 'property',
        dataType: null,
        isMonitor: false,
        isReadonly: false,
        isHistory: false,
        minValue: null,
        maxValue: null,
        unit: null,
        step: 1,
        boolFalseText: null,
        boolTrueText: null,
        enumDisplayType: 'select',
        enumItems: [],
        maxLength: 1024,
        dataDefine: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物模型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getModel(id).then(response => {
        this.form = response.data;
        // 解析数据定义
        if (this.form.dataDefine) {
          try {
            const defineData = JSON.parse(this.form.dataDefine);
            if (this.form.dataType == 'int' || this.form.dataType == 'float') {
              this.form.maxValue = defineData.max;
              this.form.minValue = defineData.min;
              this.form.step = defineData.step;
              this.form.unit = defineData.unit;
            } else if (this.form.dataType == 'enum') {
              this.form.enumDisplayType = defineData.showWay;
              this.form.enumItems = defineData.enumList.map(item => ({
                text: item.text,
                value: item.value
              }));
            } else if (this.form.dataType == 'bool') {
              this.form.boolTrueText = defineData.trueText;
              this.form.boolFalseText = defineData.falseText;
            } else if (this.form.dataType == 'string') {
              this.form.maxLength = defineData.maxLength;
            }
          } catch (e) {
            console.error('解析数据定义失败:', e);
          }
        }
        this.open = true;
        this.title = "修改物模型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 创建要提交的数据对象
          const submitData = {
            id: this.form.id,
            modelName: this.form.modelName,
            modelCode: this.form.modelCode,
            modelSort: this.form.modelSort,
            modelType: this.form.modelType,
            dataType: this.form.dataType,
            isMonitor: this.form.isMonitor,
            isReadonly: this.form.isReadonly,
            isHistory: this.form.isHistory,
            remark: this.form.remark
          };

          // 处理数据定义
          if (this.form.dataType == 'int' || this.form.dataType == 'float') {
            submitData.dataDefine = JSON.stringify({
              max: Number(this.form.maxValue),
              min: Number(this.form.minValue),
              step: this.form.step,
              type: this.form.dataType,
              unit: this.form.unit || ''
            });
          } else if (this.form.dataType == 'enum') {
            submitData.dataDefine = JSON.stringify({
              type: "enum",
              showWay: this.form.enumDisplayType,
              enumList: this.form.enumItems.map((item, index) => ({
                text: item.text,
                value: item.value
              }))
            });
          } else if (this.form.dataType == 'bool') {
            submitData.dataDefine = JSON.stringify({
              type: "bool",
              trueText: this.form.boolTrueText,
              falseText: this.form.boolFalseText
            });
          } else if (this.form.dataType == 'string') {
            submitData.dataDefine = JSON.stringify({
              type: "string",
              maxLength: Number(this.form.maxLength)
            });
          }

          if (this.form.id != null) {
            updateModel(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addModel(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物模型编号为"' + ids + '"的数据项？').then(function() {
        return delModel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/model/export', {
        ...this.queryParams
      }, `model_${new Date().getTime()}.xlsx`)
    },
    // 添加枚举项
    addEnumItem() {
      this.form.enumItems.push({
        value: '',
        text: ''
      });
    },
    // 删除枚举项
    removeEnumItem(index) {
      this.form.enumItems.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.text-center {
  text-align: center;
  line-height: 36px;
}
.el-checkbox {
  margin-right: 15px;
}
.el-radio {
  margin-right: 15px;
}
.sub-text {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  padding-top: 4px;
  text-align: left;
}
.enum-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.enum-item .el-button {
  margin-left: 10px;
}
.el-tag {
  min-width: 40px;
}
.data-define {
  text-align: left;
  line-height: 1.5;
  font-size: 13px;
}
.data-define .value {
  color: #f56c6c;
}
</style> 